﻿using OnCommon;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace OnServer
{
    public partial class Server : Form
    {
        public Server()
        {
            InitializeComponent();
        }



        private void button1_Click(object sender, EventArgs e)
        {
            SocketTcpServer server = new SocketTcpServer();
            server.Listen(20141, 100);
            server.OnCompleted += server_OnCompleted;
            server.OnFileCompleted += server_OnFileCompleted;
        }
        FileStream fs;
        void server_OnFileCompleted(SocketTcpFileData arg1, bool arg2)
        {
            if (arg1.HasFirst)
            {
                fs = File.Create(@"e:\" + arg1.FileName, 1024);
            }
            fs.Write(arg1.CurrentBytes, 0, arg1.CurrentBytes.Length);
            if (arg2)
            {
                arg1.Send(new { msg = arg1.FileName + ",长度：" + arg1.CurrentFileLen + "传输完成。存储：" + fs.Name });
                fs.Flush();
                fs.Dispose();
                this.Invoke(new Action(() =>
                {
                    this.richTextBox1.AppendText(arg1.FileName + ",长度：" + arg1.CurrentFileLen + "传输完成。存储：" + fs.Name + Environment.NewLine);
                }));
            }

        }

        void server_OnCompleted(SocketTcpData obj)
        {

            this.Invoke(new Action(() =>
            {
                this.richTextBox1.AppendText(obj.IPEndPoint.Address.ToString() + ":" + obj.IPEndPoint.Port.ToString() + Environment.NewLine);

                switch (obj.DataType)
                {
                    case PacketType.String:
                        this.richTextBox1.AppendText(obj.GetStringData() + Environment.NewLine);
                        break;
                    case PacketType.Binary:
                        this.richTextBox1.AppendText(Encoding.UTF8.GetString(obj.GetByteData()) + Environment.NewLine);
                        break;
                    case PacketType.Complex:
                        var objx = obj.GetObjData<dynamic>();
                        this.richTextBox1.AppendText(obj.GetStringData() + Environment.NewLine);
                        break;
                    default:
                        break;
                }
                this.richTextBox1.ScrollToCaret();
                this.richTextBox1.Focus();

                obj.Send(new { size = 1211, status = true });

            }));
        }

    }

}
